document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const messageInput = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    const chatMessages = document.getElementById('chat-messages');
    const emojiBtn = document.getElementById('emoji-btn');
    const emojiPicker = document.getElementById('emoji-picker');
    const closeEmoji = document.querySelector('.close-emoji');
    const emojiGrid = document.querySelector('.emoji-grid');

    // 发送消息功能
    function sendMessage() {
        const messageText = messageInput.value.trim();
        console.log(messageText)
        if (messageText) {
            // 创建新消息元素 - 修改为无气泡样式，头像在右侧
            const messageElement = document.createElement('div');
            messageElement.className = 'message sent';
            messageElement.innerHTML = `
                <div class="message-content">
                    <div class="message-info">
                        <span class="time">${getCurrentTime()}</span>
                    </div>
                    <div class="message-text">${messageText}</div>
                </div>
                <div class="avatar">
                    <img src="https://via.placeholder.com/32" alt="我的头像">
                </div>
            `;

            // 添加到聊天区域
            chatMessages.appendChild(messageElement);

            // 清空输入框并滚动到底部
            messageInput.value = '';
            scrollToBottom();

            // 模拟回复
            setTimeout(simulateReply, 1000 + Math.random() * 3000);
        }
    }

    // 模拟回复 - 保持气泡样式在左侧
    function simulateReply() {
        const replies = [
            "好的，我明白了",
            "这个想法不错！",
            "我需要再考虑一下",
            "👍",
            "什么时候开始？",
            "我同意这个方案",
            "有什么需要我帮忙的吗？",
            "😂😂😂"
        ];

        const randomReply = replies[Math.floor(Math.random() * replies.length)];
        const senders = ['张三', '李四', '王五', '赵六'];
        const randomSender = senders[Math.floor(Math.random() * senders.length)];

        const messageElement = document.createElement('div');
        messageElement.className = 'message received';
        messageElement.innerHTML = `
            <div class="avatar">
                <img src="https://via.placeholder.com/32" alt="用户头像">
            </div>
            <div class="message-content">
                <div class="message-info">
                    <span class="sender">${randomSender}</span>
                    <span class="time">${getCurrentTime()}</span>
                </div>
                <div class="message-text">${randomReply}</div>
            </div>
        `;

        chatMessages.appendChild(messageElement);
        scrollToBottom();
    }

    // 获取当前时间
    function getCurrentTime() {
        const now = new Date();
        return now.getHours().toString().padStart(2, '0') + ':' +
            now.getMinutes().toString().padStart(2, '0');
    }

    // 滚动到底部
    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 事件监听
    sendBtn.addEventListener('click', sendMessage);

    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // Emoji 选择器功能
    emojiBtn.addEventListener('click', function() {
        emojiPicker.classList.toggle('show');
    });

    closeEmoji.addEventListener('click', function() {
        emojiPicker.classList.remove('show');
    });

    emojiGrid.addEventListener('click', function(e) {
        if (e.target.tagName === 'BUTTON') {
            messageInput.value += e.target.textContent;
            messageInput.focus();
        }
    });

    // 初始化滚动到底部
    scrollToBottom();

    // 获取元素
    const imageBtn = document.getElementById('image-btn');
    const fileBtn = document.getElementById('file-btn');
    const fileInput = document.getElementById('fileInput');
    const imageInput = document.getElementById('imageInput');

    // 图片按钮点击事件 - 触发图片选择
    imageBtn.addEventListener('click', () => {
        imageInput.click(); // 触发隐藏的imageInput点击
    });

    // 文件按钮点击事件 - 触发文件选择
    fileBtn.addEventListener('click', () => {
        fileInput.click(); // 触发隐藏的fileInput点击
    });

    // 图片选择处理
    imageInput.addEventListener('change', function() {
        if (this.files && this.files[0]) {
            const file = this.files[0];
            if (file.type.startsWith('image/')) {
                sendImageMessage(file);
            } else {
                alert('请选择图片文件');
            }
            this.value = ''; // 重置input
        }
    });

    // 文件选择处理
    fileInput.addEventListener('change', function() {
        if (this.files && this.files[0]) {
            const file = this.files[0];
            sendFileMessage(file);
            this.value = ''; // 重置input
        }
    });

    // 发送图片消息函数 - 修改为无气泡样式，头像在右侧
    function sendImageMessage(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const messageElement = document.createElement('div');
            messageElement.className = 'message sent';
            messageElement.innerHTML = `
                <div class="message-content">
                    <div class="message-info">
                        <span class="time">${getCurrentTime()}</span>
                    </div>
                    <div class="message-text">
                        <img src="${e.target.result}" alt="上传的图片" class="message-image">
                    </div>
                </div>
                <div class="avatar">
                    <img src="https://via.placeholder.com/32" alt="我的头像">
                </div>
            `;
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        };
        reader.readAsDataURL(file);
    }

    // 发送文件消息函数 - 修改为无气泡样式，头像在右侧
    function sendFileMessage(file) {
        const messageElement = document.createElement('div');
        messageElement.className = 'message sent';
        messageElement.innerHTML = `
            <div class="message-content">
                <div class="message-info">
                    <span class="time">${getCurrentTime()}</span>
                </div>
                <div class="message-text file-message">
                    <div class="file-info">
                        <i class="fas ${getFileIcon(file)} file-icon"></i>
                        <div>
                            <p class="file-name">${file.name}</p>
                            <p class="file-size">${formatFileSize(file.size)}</p>
                        </div>
                    </div>
                    <a href="#" class="download-btn">下载</a>
                </div>
            </div>
            <div class="avatar">
                <img src="https://via.placeholder.com/32" alt="我的头像">
            </div>
        `;
        chatMessages.appendChild(messageElement);
        scrollToBottom();
    }

    // 辅助函数：获取文件类型图标
    function getFileIcon(file) {
        const ext = file.name.split('.').pop().toLowerCase();
        switch(ext) {
            case 'pdf': return 'fa-file-pdf';
            case 'doc':
            case 'docx': return 'fa-file-word';
            case 'xls':
            case 'xlsx': return 'fa-file-excel';
            case 'ppt':
            case 'pptx': return 'fa-file-powerpoint';
            case 'zip':
            case 'rar': return 'fa-file-archive';
            case 'txt': return 'fa-file-alt';
            default: return 'fa-file';
        }
    }

    // 辅助函数：格式化文件大小
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
        else return (bytes / 1048576).toFixed(1) + ' MB';
    }
});